package com.hiray.ui.my

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextUtils
import android.view.View
import com.hiray.App
import com.hiray.R
import com.hiray.di.component.DaggerAccountComponent
import com.hiray.mvp.p.UserPresenter
import com.hiray.ui.TextWatcherAdapter
import com.hiray.util.Toasty
import kotlinx.android.synthetic.main.activity_modify_password.*
import javax.inject.Inject

class ModifyPasswordActivity : AppCompatActivity() {

    @Inject
    lateinit var userPresenter: UserPresenter


    var inputChangeWatcher: TextWatcherAdapter = object : TextWatcherAdapter() {
        override fun afterTextChanged(s: Editable?) {
            submit.isEnabled =
                    !captcha.text.toString().isEmpty()
                    && !password.text.toString().isEmpty()
                    && !confirmPassword.text.toString().isEmpty()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_modify_password)

        DaggerAccountComponent
                .builder()
                .appComponent((application as App).appComponent)
                .build()
                .inject(this)

        observeUserInputChange()
    }

    //获取修改密码验证码
    fun getCaptcha(v: View) {
        userPresenter.getModifyPasswordCaptcha()
        captchaTextView.start()
    }

    private fun observeUserInputChange() {
        captcha.addTextChangedListener(inputChangeWatcher)
        password.addTextChangedListener(inputChangeWatcher)
        confirmPassword.addTextChangedListener(inputChangeWatcher)
    }

    fun confirmModifyPassword(v: View) {
        if (checkParameter()) {
            userPresenter.modifyPassword()
        }
    }

    private fun checkParameter(): Boolean {
        val captchaString = captcha.text.toString()
        val passwordString = password.text.toString()
        val confirmedPasswordString = confirmPassword.text.toString()
        if (TextUtils.isEmpty(captchaString)) {
            Toasty.message(R.string.captcha_empty)
            return false
        } else if (TextUtils.isEmpty(passwordString)) {
            Toasty.message(R.string.password_empty)
            return false
        } else if (TextUtils.isEmpty(confirmedPasswordString)) {
            Toasty.message(R.string.please_input_new_pwd_again)
            return false
        } else if (!TextUtils.equals(passwordString, confirmedPasswordString)) {
            Toasty.message(R.string.password_inconsistent)
            return false
        }
        return true
    }
}


